package com.demo;

public class Demo05 {
    public static String parseToMoney(double number) {
        // 将数字转成字符串
        String stringNumber = Double.toString(number);
//        String stringNumber = String.valueOf(number);
        // 以"."为分隔符，将数字分为整数部分和小数部分
        String[] split = stringNumber.split("\\.");
        if(split.length <= 0){
            return "";
        }
        String intPart = split[0];
        String decimalPart = split.length > 1? split[1] : "";
        // 对整数部分添加千分位逗号
        StringBuffer formattedInteger = new StringBuffer();
        int length = intPart.length();
        for (int i = 0; i < length; i++) {
            // 遍历整数部分，每三位添加一个逗号
            if(i > 0 && (length - i) % 3 == 0){
                formattedInteger.append(",");
            }
            formattedInteger.append(intPart.charAt(i));
        }
        return formattedInteger.toString() + "." + decimalPart;
    }
    public static void main(String[] args) {
        System.out.println(parseToMoney(1234.56));
        System.out.println(parseToMoney(123456789));
        System.out.println(parseToMoney(1087654.321));
        System.out.println(parseToMoney(98765));
        System.out.println(parseToMoney(7654321.9));
    }
}
